package vcp.server.requesthandler;

import java.util.ArrayList;
import java.util.List;

import ocsf.server.ConnectionToClient;
import vcp.client.forms.ApproveCostForm.ApproveCostContainer;
import vcp.client.request.SiteCostApproveRequest;
import vcp.client.request.response.ResponseRequest;
import vcp.entity.Site;
import vcp.entity.SiteCostUpdates;
import vcp.enums.SiteEnum.SiteCostsUpdateStatus;
import vcp.server.DAO.SiteCostUpdatesDAO;
import vcp.server.DAO.SiteDAO;
import vcp.server.interfaces.IServer;
/**
 * 
 * @author VCP team
 *<p>
 *class handles requset from client to approve costs
 *</p>
 */
public class SiteCostApproveRequestHandler extends RequestHandler <SiteCostApproveRequest>
{
	/**
	 * class constructor
	 * @param server
	 */
	public SiteCostApproveRequestHandler ( IServer server )
	{
		super(server);
	}

	@Override
	public void execute ( SiteCostApproveRequest request, ConnectionToClient client )
	{
		SiteCostUpdatesDAO siteCostUpdatesDAO = new SiteCostUpdatesDAO();
		SiteDAO siteDAO = new SiteDAO();

		ArrayList <SiteCostUpdates> reviewedList = new ArrayList <>();
		List <SiteCostUpdates> pendingList = siteCostUpdatesDAO.findAllPendingSiteCostUpdates();

		for ( ApproveCostContainer siteAproveCostForm : request.getApproveCostForm().getFroms() )
		{
			for ( SiteCostUpdates siteCostUpdates : pendingList )
			{
				if ( siteCostUpdates.getSiteEnum() == siteAproveCostForm.getSiteName() )
				{
					if ( siteAproveCostForm.getUpdateStatus() == SiteCostsUpdateStatus.APPROVED )
					{
						siteDAO.updateSingleUsePricePerHour(siteCostUpdates.getSiteEnum().getSiteID(), siteCostUpdates.getSingleUsePricePerHour());
						siteDAO.updateOrderAheadPricePerHour(siteCostUpdates.getSiteEnum().getSiteID(), siteCostUpdates.getOrderAheadPricePerHour());
						siteDAO.updateCasualPriceSingleCar(siteCostUpdates.getSiteEnum().getSiteID(), siteCostUpdates.getCasualPriceSingleCar());
						siteDAO.updateFullPriceSingleCar(siteCostUpdates.getSiteEnum().getSiteID(), siteCostUpdates.getFullPriceSingleCar());
					}
					else
					{
						Site site = siteDAO.findByID(siteAproveCostForm.getSiteName().getSiteID());

						siteCostUpdates.setSingleUsePricePerHour(site.getSingleUsePricePerHour());
						siteCostUpdates.setOrderAheadPricePerHour(site.getOrderAheadPricePerHour());
						siteCostUpdates.setCasualPriceSingleCar(site.getCasualPriceSingleCar());
						siteCostUpdates.setFullPriceSingleCar(site.getFullPriceSingleCar());
					}

					siteCostUpdates.setStatus(siteAproveCostForm.getUpdateStatus());
					siteCostUpdates.setHistory(true);
					siteCostUpdatesDAO.updateCostsStatus(siteCostUpdates.getID(), siteCostUpdates.getStatus());
					siteCostUpdatesDAO.updateIsHistory(siteCostUpdates.getID(), siteCostUpdates.isHistory());
					reviewedList.add(siteCostUpdates);
				}
			}
		}

		this.sendResponseRefresh(reviewedList, client);
		this.sendResponse(new ResponseRequest(request.getRequestID(), reviewedList), client);
	}

}
